package org.manager.upload;

import java.io.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.ServletInputStream;

public class RequestUpload {
	
    private String saveDir = null;//用于设置保存在哪个目录下
    private String savePath=null;//用于设置所要保持文件的完整路径,即saveDir+文件名
    private String filename[] = new String[50];//文件名数组
    private int count=0;//文件个数
    private boolean existTheFile=true;//用于判断是否有存在文件(比如有三个上传控件,第二个为空,其他都文件对象)
    private String filetype[] = new String[50];//扩展名
    private String sperator = null;//头尾信息跟上传文件的分隔符
    private byte[] block = new byte[4096];//每次读取一行(使用Ｓervlet流),block保存每行的数据
    private int L = -1;//用于获取ServletInputStream.readLine方法的返回值
    boolean over=false;//此次传输是否结束
    
/**
* 构造函数,参数表示文件所保持的路径位置
*/
    public RequestUpload(String savepath) {
       saveDir = savepath;
    }
/**
* 上传文件的函数,参数为request
*/
    public boolean start (HttpServletRequest request) throws Exception {
      if (saveDir == null) {
         return false;
      }
      count=0;
      String s =null;
      ServletInputStream in = request.getInputStream ();
      L = in.readLine (block, 0, block.length);//读取第一行即"-----------------------------7d8261a105a4"和换行
      sperator = new String (block, 0, L);//转换成字符串
      sperator=sperator.substring(0, sperator.length()-2);//取"-----------------------------7d8261a105a4"
      do{
       try{
              L = in.readLine (block, 0, block.length);//读取第二行即"Content-Disposition: form-data; name="file1"; filename="F:\zsy.txt""包括换行
              String second = new String (block, 0, L);//转换成字符串
              int index1 = second.indexOf ("filename=\"");
              int index2=0;
              if (index1 != -1) {
               second = second.substring (index1 + 10);//filename="之后的字符串
                  index1 = second.lastIndexOf ('\\');
                  index2=second.lastIndexOf ('.');
                  filename[count]=second.substring(index1+1,index2);            
                  index1 = second.indexOf ("\"");
                  filetype[count]=second.substring(index2,index1);
                  L = -1;
              }
              existTheFile=true;
          }catch(Exception e){
           existTheFile=false;//当上传控件,没有文件时就抛出异常.即不存在文件
          }
          if(!existTheFile){
              in.readLine (block, 0, block.length);//读取第三行
              in.readLine (block, 0, block.length); //读取第四行
              in.readLine (block, 0, block.length);//读取第5行
              L=in.readLine (block, 0, block.length);//读取第6行
              s = new String (block, 0, L);
              s=s.substring(0,sperator.length()+2);
              if(s.equals(sperator.concat("--"))){//判断是不是"-----------------------------7d8261a105a4--"
               //不能使用sperator+"--"
               over=true;
                   break;//如果已经到结束标志,退出循环               
              }
              else
                   continue;//如果未到结束标志,退出本次循环,继续下一次
           }
           this.savePath=this.getPath(saveDir, filename[count], filetype[count], 0);
           File uploadFile = new File(this.savePath);
           if(!uploadFile.exists()){
        	   File dir = new File(saveDir);
        	   if(!dir.exists()){
        		   dir.mkdirs();
        	   }
        	   uploadFile.createNewFile();
           }
           FileOutputStream out = new FileOutputStream (this.savePath);
           in.readLine (block, 0, block.length);//读取第三行
           in.readLine (block, 0, block.length); //读取第四行   
           try {
               L = in.readLine (block, 0, block.length);////读取第五行,第五行就是是所传文件内容            
               while (L != -1) {
               s = new String (block, 0, L);
               if (s.length () >=sperator.length()) {                 
                    if ((s.substring(0, sperator.length())).equals (sperator)) {//判断文件内容是否结束
                    if((s.substring(0, sperator.length()+2)).equals(sperator.concat("--")))//判断是否到最末尾
                           over=true;//所有文件传输结束
                         break;
                    }
                }
                out.write (block, 0, L);//写
                L = in.readLine (block, 0, block.length);//读
            }
            out.close ();
          } catch (Exception e) {
             out.close ();
             over=false;
             File tmp = new File (saveDir,savePath);
             if (!tmp.delete()) {
                 System.out.println("操作失败:未完成文件未删除");
             }
          }
          count++;
          if(over) break;
       }while(true);     
       return over;      
    }
/**
* 获取文件名(包括扩展名)
*/
    public String[] getFileName () {
      String temp[]=new String[count];
      for(int i=0;i<count;i++)
       temp[i]=filename[i]+filetype[i];
      return temp;
    }
/**
* 此方法防止因文件名遇到相同而覆盖,自动修改文件名,修改方式跟windows原理一样
*/
    public String getPath(String SaveDir,String FileName,String FileType ,int deep){
    File f=null;
    String path=null;
    f=new File(SaveDir + "\\" + FileName+"("+deep+")"+FileType);
    if(f.exists()){
      return getPath(SaveDir,FileName,FileType,++deep);
    }
    else{
    // if(deep==0) return (SaveDir + "\\" + FileName+FileType);
     path=SaveDir + "\\" + FileName+"("+deep+")"+FileType;   
     return path;
    }
    }
}